/******************************************************
 * Graduate Project TU eTour
 * @author Hui Liu
 * @dueDate May 14, 2011
 * @purpose
 * This is the main activity of this project
 * It shows a campus map with marker to different locations
 * Track current device position 
 * @algorithm
 *  See map class
 * 
 * @input
 * 
 * @output
 *
*********************************************************/
package org.TUApp.eTour;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
//import android.view.MenuItem;

import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;


// TODO: Auto-generated Javadoc
/**
 * The Class MyMap.
 */
public class MyMap extends MapActivity{
   
   /** The map view. */
   private MapView map;
   
   /** The map controller. */
   private MapController controller;
   
   /** The building l. */
   private CampusMapOverlay buildingL;
   
   /** The parking l. */
   private CampusMapOverlay parkingL;
   
   /** The visitor l. */
   private CampusMapOverlay visitorL;
   
   /** The stop l. */
   private CampusMapOverlay stopL;
   //private String best;
   //private LocationManager lm;
   //private Location lastLocation;

//   private Cursor[] campusCursor[]; 
   /**
    * The provider authority.
    */
   public static final String AUTHORITY = CampusMapData.AUTHORITY;
   

   /** The Constant LOCATION_DIALOG. */
//   static final private int LOCATION_DIALOG = 1;
   
   /** The Constant SHOW_PREFERENCES. */
   static final private int SHOW_PREFERENCES = 1;  
   
   /** The Constant SHOW_LAYERS. */
   static final private int SHOW_LAYERS = 2;  
   //the minimum time interval for notifications, in milliseconds.
   /** The Constant FREASH_RATE. */
//   static final private long FREASH_RATE = 15000;
   //the minimum distance interval for notifications, in meters
   /** The Constant FREASH_DIST. */
//   static final private float FREASH_DIST = 20;  

   /* (non-Javadoc)
    * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle)
    */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      
      setContentView(R.layout.main);
      initMapView();
      initCampusMap();
//      lastLocation = lm.getLastKnownLocation(best);
//      updateWithNewLocation(lastLocation);
      initMyLocation();
//      refreshEvents();
   }

   /** Find and initialize the map view. */
   private void initMapView() {
      map = (MapView) findViewById(R.id.map);
      controller = map.getController();
      map.setSatellite(true);
      map.setTraffic(false);
//      map.setStreetView(true);
      map.setBuiltInZoomControls(true);
   }

   /** Start tracking the position on the map. using MyLocationOverlay
  */ 
   private void initMyLocation() {
      final MyLoc myLocationL = new MyLoc(this, map);
      if (!myLocationL.enableMyLocation()){
			Toast.makeText(this, "Your location provider has been disabled \n-- please enable it", Toast.LENGTH_LONG).show();
      }
//      myLocationL.enableCompass(); // does not work in emulator
      myLocationL.runOnFirstFix(new Runnable() {
         public void run() {
            // Zoom in to current location
            controller.setZoom(map.getMaxZoomLevel()-4);
            controller.animateTo(myLocationL.getMyLocation());
         }
      });
      
      map.getOverlays().add(myLocationL);
      
   }
   
   /**
	 * Start tracking the position on the map. using Location
	 * 
	 * @param location
	 *            the location
   private void updateWithNewLocation(Location location) {
	   
	   
	   
   }
	 */
  /** Mark campus locations on the map. */
  private void initCampusMap(){
	  int B = 0;
	  int P = 1;
	  int V = 2;
	  int S = 3;

	    Uri campusURI = CampusMapData.CONTENT_URI;
//	    int test = uriMatcher.match(buildingURI);
	    Drawable marker[] = new Drawable[]{getResources().getDrawable(R.drawable.academic_building),
	    		getResources().getDrawable(R.drawable.parking),
	    		getResources().getDrawable(R.drawable.vistor_parking),
	    		getResources().getDrawable(R.drawable.stop)}; 
	    Cursor campusCursor[] = {getContentResolver().query(Uri.withAppendedPath(campusURI, "/B/ltype"),null, null, null, null),
	    		getContentResolver().query(Uri.withAppendedPath(campusURI, "/P/ltype"), null, null, null, null),
	    		getContentResolver().query(Uri.withAppendedPath(campusURI, "/V/ltype"), null, null, null, null),
	    		getContentResolver().query(CampusMapData.STOP_URI,null, null, null, null),
	    };
	    
	    Context context = getApplicationContext();
	    buildingL = new CampusMapOverlay(marker[B], campusCursor[B], map, "B");
	    if (Layers.markBuilding(context)) map.getOverlays().add(buildingL);
	    parkingL = new CampusMapOverlay(marker[P], campusCursor[P], map, "P");
	    if (Layers.markParking(context)) map.getOverlays().add(parkingL);
	    visitorL = new CampusMapOverlay(marker[V], campusCursor[V], map, "V");
	    if (Layers.markVisitor(context)) map.getOverlays().add(visitorL);
	    stopL = new CampusMapOverlay(marker[S], campusCursor[S], map, "S");
	    if (Layers.markStop(context)) map.getOverlays().add(stopL);
	    map.invalidate();

	    controller.setCenter(buildingL.getCenter());
        controller.setZoom(map.getMaxZoomLevel()-4);

   }

   /* (non-Javadoc)
    * @see com.google.android.maps.MapActivity#isRouteDisplayed()
    */
   @Override
   protected boolean isRouteDisplayed() {
      // Required by MapActivity
      return false;
   }
  
   /* (non-Javadoc)
    * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
    */
   @Override
   public boolean onCreateOptionsMenu(Menu menu){
	   super.onCreateOptionsMenu(menu);
	   MenuInflater inflater = getMenuInflater();
	   inflater.inflate(R.menu.etour_menu, menu);
	   return true;
   }

   /* (non-Javadoc)
    * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
    */
   public boolean onOptionsItemSelected(MenuItem item) {
	      super.onOptionsItemSelected(item);
	      switch (item.getItemId()) {
	        case R.id.preferences: {
	          Intent i = new Intent(this, Preferences.class);
	          startActivityForResult(i, SHOW_PREFERENCES);
	          return true;
	        }
	        case R.id.layers: {
		          Intent i = new Intent(this, Layers.class);
		          startActivityForResult(i, SHOW_LAYERS);
		          return true;
		        }
	        case R.id.about: {
		          Intent i = new Intent(this, About.class);
		          startActivity(i);
		          break;
		        }
	        case R.id.search: {
		          String busTime = Utils.nextBus("gold", "unio");
		          if (busTime!=null)
		  			Toast.makeText(this, "The next bus will arrive in " + busTime + " minutes", Toast.LENGTH_LONG).show();
		          break;
		        }

	      } 
	      return false;
	    }
   
   /**
	 * Update from preferences.
	 */
   private void updateFromPreferences() {
	   Context context = getApplicationContext();
	      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
	      

	      /**
	      eventReminder = prefs.getBoolean(Preferences.EVENT_REMINDER, true));
	      updateFreq = Integer.parseInt(prefs.getString(Preferences.PREF_UPDATE_FREQ, "0"));
	      busReminder = prefs.getBoolean(Preferences.BUS_REMINDER, true);
	*/      
	    }
   
   /**
	 * Update from layers.
	 */
   private void updateFromLayers() {
	   Context context = getApplicationContext();
	    if (Layers.markBuilding(context)){
	    	if (!map.getOverlays().contains(buildingL))
	    		map.getOverlays().add(buildingL);
	    }else
	    	map.getOverlays().remove(buildingL);
	    if (Layers.markParking(context)){
	    	if (!map.getOverlays().contains(parkingL))
	    		map.getOverlays().add(parkingL);
	    }else
	    	map.getOverlays().remove(parkingL);
	    if (Layers.markVisitor(context)) {
	    	if (!map.getOverlays().contains(visitorL))
	    		map.getOverlays().add(visitorL);
	    }else
	    	map.getOverlays().remove(visitorL);
	    if (Layers.markStop(context)) {
	    	if (!map.getOverlays().contains(stopL))
	    		map.getOverlays().add(stopL);
	    }else
	    	map.getOverlays().remove(stopL);
	}
   
   /* (non-Javadoc)
    * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
    */
   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);

     switch (requestCode) {
	     case (SHOW_PREFERENCES): {
	             updateFromPreferences();
	             break;
	     }
	     case (SHOW_LAYERS): {
	        	 updateFromLayers();
	        	 break;
		 }
     } 
   }
   
   /**
	 * Refresh events.
   private void refreshEvents() {
		  // Get the XML
		  URL url;
		  try {
		    String eventFeed = getString(R.string.event_feed);
		    url = new URL(eventFeed);
		         
		    URLConnection connection;
		    connection = url.openConnection();
		       
		    HttpURLConnection httpConnection = (HttpURLConnection)connection; 
		    int responseCode = httpConnection.getResponseCode(); 

		    if (responseCode == HttpURLConnection.HTTP_OK) { 
		      InputStream in = httpConnection.getInputStream(); 
		          
		      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		      DocumentBuilder db = dbf.newDocumentBuilder();

		      // Parse the event feed.
		      Document dom = db.parse(in);      
		      Element docEle = dom.getDocumentElement();
		        
		      // preparing the database
		     
 		      // Get a list of each earthquake entry.
 
		      NodeList nl = docEle.getElementsByTagName("entry");
		      if (nl != null && nl.getLength() > 0) {
		        for (int i = 0 ; i < nl.getLength(); i++) {
		          Element entry = (Element)nl.item(i);
		          Element title = (Element)entry.getElementsByTagName("title").item(0);
		          Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
		          Element when = (Element)entry.getElementsByTagName("updated").item(0);
		          Element link = (Element)entry.getElementsByTagName("link").item(0);

		          String details = title.getFirstChild().getNodeValue();
		          String hostname = "http://earthquake.usgs.gov";
		          String linkString = hostname + link.getAttribute("href");

		          String point = g.getFirstChild().getNodeValue();
		          String dt = when.getFirstChild().getNodeValue();  
		          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
		          Date qdate = new GregorianCalendar(0,0,0).getTime();
		          try {
		            qdate = sdf.parse(dt);
		          } catch (ParseException e) {
		            e.printStackTrace();
		          }

		          String[] location = point.split(" ");
		          Location l = new Location("dummyGPS");
		          l.setLatitude(Double.parseDouble(location[0]));
		          l.setLongitude(Double.parseDouble(location[1]));

		          String magnitudeString = details.split(" ")[1];
		          int end =  magnitudeString.length()-1;
		          double magnitude = Double.parseDouble(magnitudeString.substring(0, end));
		              
		          details = details.split(",")[1].trim();
		              
//		          Quake quake = new Quake(qdate, details, l, magnitude, linkString);

		          // Process a newly found earthquake
//		          addNewQuake(quake);
		        }
		      }
		    }
		  } catch (MalformedURLException e) {
		    e.printStackTrace();
		  } catch (IOException e) {
		    e.printStackTrace();
		  } catch (ParserConfigurationException e) {
		    e.printStackTrace();
		  } catch (SAXException e) {
		    e.printStackTrace();
		  }
		  finally {
		  }
		}
			 */

/**
@Override
public void onLocationChanged(Location arg0) {
	// TODO Auto-generated method stub
	//	Toast.makeText(this, "The current location is (lat:" + arg0.getLatitude() + ", lng:" + arg0.getLongitude(), Toast.LENGTH_LONG).show();
	
	
}

@Override
public void onProviderDisabled(String provider) {
	// TODO Auto-generated method stub
	//log("\nProvider disabled: " + provider);
	if (best.equalsIgnoreCase(provider)){
		
	}
	
}

@Override
public void onProviderEnabled(String provider) {
	// TODO Auto-generated method stub
	updateWithNewLocation(null);
	
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
	// TODO Auto-generated method stub
	
}
**/

}
